
/**
 * 广告清道夫
 */
var adClearer = {
	log:true,
	clearType: 3, // 1：css注入清楚 2：display:none隐藏  3：1+2的方式 document
	lastDo: Date.now(),
	config:null,
	addCSS:function(targetDocument,cssText){
	     var style = targetDocument.createElement('style'), //创建一个style元素
	        head = targetDocument.head || targetDocument.getElementsByTagName('head')[0]; //获取head元素
	      style.type = 'text/css'; //这里必须显示设置style元素的type属性为text/css，否则在ie中不起作用
	      if(style.styleSheet){ //IE
	        var func = function(){
	          try{ //防止IE中stylesheet数量超过限制而发生错误
	            style.styleSheet.cssText = cssText;
	          }catch(e){
	    
	          }
	        }
	        //如果当前styleSheet还不能用，则放到异步中则行
	        if(style.styleSheet.disabled){
	          setTimeout(func,10);
	        }else{
	          func();
	        }
	      }else{ //w3c
	        //w3c浏览器中只要创建文本节点插入到style元素中就行了
	        var textNode = targetDocument.createTextNode(cssText);
	        style.appendChild(textNode);
	      }
	      head.appendChild(style); //把创建的style元素插入到head中  
	},
	
	generateCss:function(tagName,idName,className,attrName,text){
		var res = "";
		res += adClearer.cs(1,tagName);
		res += adClearer.cs(2,idName);
		res += adClearer.cs(3,className);
		res += adClearer.cs(4,attrName);
		res += adClearer.cs(5,text);
		return res;
	},
	
	getJqString: function(i,k){
		switch(i-0){
			case 1:
		   	    return k;
			case 2:
			    return "#"+k;
			case 3:
			    return "."+k;
			case 4:
			    return "[name="+k+"]";
			case 5:
			    return "a:contains("+k+"),span:contains("+k+")";
			default :
			return k;
		}
	},
	cs:function(ind,keys){
		var res = "";
		if(keys && keys.length > 0){
			for(var i = 0 ; i < keys.length; i++){
				var item = keys[i];
				var cssChoose = adClearer.getJqString(ind,item);
				if(cssChoose)res += cssChoose + ",";
			}
			if(res)res = res.substring(0,res.length-1); // 去除最后的逗号
		}
		if(res){
			res += "{\r\n  display:none !important;\r\n} \r\n";
		}
		return res;
	},
	clear:function(tagName,idName,className,attrName,text,existLen,callback){
		
		// 隐藏元素
		if(adClearer.clearType == 1 || adClearer.clearType == 3){
			var cssText = adClearer.generateCss(tagName,idName,className,attrName,text,existLen);
			adClearer.addCSS(document,cssText);
			if(callback)setTimeout(function() {callback();}, 100);
			if(adClearer.clearType == 1 )return;
		}
		
		// 删除元素
		var countclear = 15,rcout =0;
		var doneLen = 0,lastDoneLen = -1;
		var clearTimer = setInterval(function(){
			countclear -- ;
			rcout ++;
			var curDoneLen = 0;
			// try{
				 curDoneLen = adClearer.clearDom(tagName,idName,className,attrName,text);
			// }catch(err){
			// 	console.info(err)
			// }
			doneLen += curDoneLen;
			if((lastDoneLen >2 && curDoneLen===0) || countclear < 0){
				clearInterval(clearTimer);
				if(callback)callback();
				console.info("循环次数："+rcout);
			}
			if(existLen && doneLen >= existLen){
				clearInterval(clearTimer);
				if(callback)callback();
				console.info("说循环次数："+rcout);
			}
			if(curDoneLen == 0)lastDoneLen ++;
		},300);
	},
	
	/**
	 * 返回本轮删除的对象数量
	 * @param {Object} tagName
	 * @param {Object} idName
	 * @param {Object} className
	 * @param {Object} attrName
	 * @param {Object} text
	 */
	clearDom:function(tagName,idName,className,attrName,text){
		
		if(!adClearer.log ){
			console.info(tagName);
			console.info(idName);
			console.info(className);
			console.info(attrName);
			console.info(text);
		}
		
		function sp(key){
			var dn = key.split(">");
			if(!dn || dn.length == 0)dn=[key];
			if(dn.length != 2)return dn;
			var dp = dn[1].split("#");
			if(!dp || dp.length != 2)return dn;
			dn[1] = dp[0];
			dn[2] = dp[1];
			return dn;
		}
		function rm(ind,keys){
			var c = 0;
			for(var i=0; i < keys.length;i ++){
				var key = keys[i];
				var dn = sp(key);
				if(!dn||!dn[0])continue;
				var nofull = $(adClearer.getJqString(ind,dn[0]));
				if(dn.length == 3 && nofull && nofull.length > 0){ // 移除父节点
					for(var io =0;io < nofull.length;io++){
						if(ind==5 && nofull.eq(io).text() != dn[0])continue;
						var ps = adClearer.getJqString(dn[1],dn[2]);
						var nop = nofull.eq(io).parents(ps);
						nop.remove();
					}
				}else if(nofull && nofull.length > 0){
					nofull.remove();
					c ++;
				}
			}
			return c;
		}
		adClearer.log = true;
		var c=0,len=0;
		if(tagName){
			len += tagName.length;
			c += rm(1,tagName);
		}
		
		if(idName){
			len += idName.length;
			c += rm(2,idName);
		}
		
		if(className){
			len += className.length;
			c += rm(3,className);
		}
		
		if(attrName){
			len += attrName.length;
			c += rm(4,attrName);
		}
		if(text){
			len += text.length;
			c += rm(5,text);
		}
		return c ;
	},
	
	clearBySetting:function(callback,done){
		var url = getRootPath();
		var yuming = getYuming(url);
		try{
			chrome.storage.sync.get(yuming, function(res) {
				res = res[yuming];
				adClearer.config = res;
				if(res){
					if(res.status != "on")return;
					var tagName = res.tagName ? res.tagName.split(",") || [] : [];
					var idName = res.idName ? res.idName.split(",") || [] : [];
					var className = res.className ? res.className.split(",") || [] : [];
					var attrName = res.name ? res.name.split(",") || [] : [];
					var text = res.text ? res.text.split(",") || [] : [];
					var cssJson = res.cssJson || "{}";
					adClearer.clearType = res.clearType;
					cssJson = JSON.parse(cssJson);
					adClearer.clear(tagName,idName,className,attrName,text,null,function(){
						adClearer.setAttrByCssJson(cssJson);
					});
					if(res.switchOn){
						adClearer.clearAuto($("html"));
					}
					adClearer.setDomChangeListener(); // 监听页面变动，变动时执行清理
				}else{
					if(callback)callback();
				}
				if(done)done();
			});
		}catch(e){
			console.info(e)
		}
	},
	setAttrByCssJson: function(cssJson){
		for(var key in cssJson){
			var value = cssJson[key];
			if(!value || !value.type || !value.css)continue;
			var nofull = null;
			switch(value.type){
				case 'tagName':
				    nofull =  document.getElementsByTagName(key);
				    break;
				case 'idName':
				    nofull =  document.getElementById(key);
				    break;
				case 'className':
				    nofull =  document.getElementsByClassName(key);
				    break;
				case 'name':
				    nofull =  document.getElementsByName(key);
				    break;
				default:
				    continue;
			}
			if(!nofull)continue;
			
			for(var len =0; len < nofull.length; len ++){
				nofull[len].setAttribute("style",value.css);
			}
		}
	},
	clearCVNS : function(){
		console.info("自动清除cvns广告")
		var tagName = ["header"];
		var idName = ["toolBarBox","csdn-toolbar"];
		var className = ["column-group","blog_container_aside","csdn-side-toolbar"];
		var attrName = [];
		// var len = tagName.length + idName.length +className.length +attrName.length ;
		adClearer.clear(tagName,idName,className,attrName,null,function(){
			var dom1 = document.getElementsByTagName("main")[0];
			if(dom1)dom1.setAttribute("style","width:100%");
		});
	},
	
	clearBaidu : function(){
		console.info("自动清除百度文库广告");
		var oldbody = null;
		var tagName = ["header"];
		var idName = ["app-left","app-right","app-reader-below"];
		var className = ["no-full-screen"
		                 ,"pc-cashier-card"
						 ,"vip-member-pop-content"
		                 // ,"center-wrapper"
						 ,"fold-page-content"
						 ,"no-full-screen"
						 ,"hx-recom-wrapper"
						 ,"app-reader-below"
						 , "hx-warp"
						 ];
		var attrName = [];
		// var len = tagName.length + idName.length +className.length +attrName.length ;
		adClearer.clear(tagName,idName,className,attrName,null,function(){
			var dom1 = document.getElementsByClassName("center-wrapper")[0];
			if(dom1){   dom1.setAttribute("style","width:100%");}
			var dom1 = document.getElementsByClassName("ql-editor")[0];
			if(dom1)dom1.setAttribute("style","height:auto;");
		});
		// if(oldbody && oldbody.length > 200){
		// 	document.getElementsByClassName("center-wrapper")[0].innerHTML=oldbody;
		// }
	},
	clearBaidu1 : function(){
		console.info("自动清除百度搜索页广告");
		var ads = $(":contains(广告)");
		var parents = ads.parents(".c-container");
		parents.remove();
	},
	clearjianshu : function(){
		console.info("自动清除简书广告");
		var tagName = ["header","aside","footer"];
		var idName = [];
		var className = ["-umr26"];
		var attrName = [];
		// var len = tagName.length + idName.length +className.length +attrName.length ;
		adClearer.clear(tagName,idName,className,attrName,null);
	},
	
	setDomChangeListener: function(){
		// 当观察到变动时执行的回调函数
		var callback = function(mutationsList) {
			if(Date.now() - adClearer.lastDo < 5000)return;
		    for(let mutation of mutationsList) {
		        if (mutation.type === 'childList') {
		            adClearer.clearBySetting();
					adClearer.lastDo = Date.now() ;
					break;
		        } else if(mutation.type === 'attributes') {
		            
		        } else if(mutation.type === 'characterData') {
		            adClearer.clearBySetting();
					adClearer.lastDo = Date.now() ;
					break;
		        }
		    }
		}
		// 创建一个观察器实例并传入回调函数
		var observer = new MutationObserver(callback);
		// 选择需要观察变动的节点
		var targetNode = document.body;
		// 观察器的配置（需要观察什么变动）
		var config = { attributes: true, childList: true, subtree: true, characterData: true};
		// 以上述配置开始观察目标节点
		observer.observe(targetNode, config);
		// 之后，可停止观察
		// observer.disconnect();
	},
	
	isOnlyOne : function(d){
		var p = d.parent();
		var r = d;
		if(p){
			if(p.children().length > 1){
				r = d;
			}else{
				r = adClearer.isOnlyOne(p);
			}
		}else{
			r = d;
		}
		return r;
	},
	clearAuto: function($parent,flag){
		var countAutoClear = 10;
		var autoClearTimer = setInterval(function(){
			countAutoClear -- ;
			if(countAutoClear < 0)clearInterval(autoClearTimer);
			var $img = $parent.find("img");
			var p = null;
			// 固定页广告
			$fix = $parent.find("[style*='position:fixed'][style*='z-index']");
			$fix.remove();
			
			// 图片广告
			for(var i =0 ; i < $img.length; i ++){
				var temImg = $img.eq(i);
				var imgSrc = temImg.attr("src");
				if(imgSrc && imgSrc.indexOf("http") > -1){ // 视为广告
					var r = adClearer.isOnlyOne(temImg);
					if(r)r.remove(); // 移除广告节点
				}else if( (p = temImg.parent()).is("a")){ // 父节点是a标签的视为广告
				    var hrefStr = p.attr("href");
					if(hrefStr && hrefStr.indexOf("http") > -1){
						var r = adClearer.isOnlyOne(temImg);
						if(r)r.remove(); // 移除广告节点
					}
				}
			}
			// a标签广告
			var $a = $parent.find("a[href^=http]");
			for(var i =0 ; i < $a.length; i ++){
				var tema = $a.eq(i);
				var r = adClearer.isOnlyOne(tema);
				if(r)r.remove(); // 移除广告节点
			}
			// iframe 广告,过滤所有非同源的iframe
			var $iframe = $parent.find("iframe[src^=http]");
			for(var i =0 ; i < $iframe.length; i ++){
				var tema = $iframe.eq(i);
				var r = adClearer.isOnlyOne(tema);
				if(r)r.remove(); // 移除广告节点
			}
		},200);
	},
	// 查找iframe里的广告
	findInIframe : function($parent){
		var iframes =  $parent.find("iframe");
		if(iframes.length > 0){
			for(var i=0;i<iframes.length;i++){
				 var iframeTem = $(iframes[i].contentWindow.document);
				 if(iframeTem.height() <= 0 ){
				 	iframeTem.remove();
				 }else{
				 	adClearer.clearAuto(iframeTem,1);
				 	adClearer.findInIframe(iframeTem);
				 }
			}
		}
	}
}

setTimeout(function() {
	adClearer.clearBySetting(function(){
		var url = getRootPath();
		if(url){
			if(url.indexOf("csdn") > -1){
				adClearer.clearCVNS();
			}else if(url.indexOf("wenku.baidu") > -1){
				adClearer.clearBaidu();
			}else if(url.indexOf("jianshu") > -1){
				adClearer.clearjianshu();
			}else if(url.indexOf("www.baidu.com")){ 
				adClearer.clearBaidu1();
			}else{
				console.info("未设置广告清除");
			}
		}else{
			console.info("无法获取url");
		}
	},function(){
		var url = getRootPath();
		if(url.indexOf("blog.csdn.net") > -1){
			// 解锁需要关注解锁的博客
			$("#article_content").css("height","auto");
			$(".hide-article-box ").remove();
		}
	});
	
	
}, 10);

